package com.qd.system.service.org;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.common.sys.constant.Constants;
import com.qd.common.sys.domain.entity.org.OrgPersonDTO;
import com.qd.common.sys.domain.entity.org.OrgPersonDisplayDTO;
import com.qd.system.mapper.OrgPersonMapper;
import com.qd.system.model.OrgPerson;
import com.qd.system.model.Person;
import com.qd.system.service.person.PersonService;
import com.qd.system.service.user.UserOperatorService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

import static java.util.stream.Collectors.toList;

/**
 * @author sjk
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OrgPersonService extends BaseService<OrgPersonMapper, OrgPerson> {

    private static final String PREFIX_ID = "sys_org_person_orgPersonId_{0}";
    private static final String PREFIX_ORG_LIST = "sys_org_person_orgIds_{0}";
    private static final String PREFIX_UNIQUE_SYS_ORG_PE = "sys_org_person_personId_{0}_orgId_{1}";

    private final RedisTemplateUtil<OrgPerson> redisTemplateUtil;
    private final PersonService personService;
    private final OrgService orgService;

    private static String buildPrefixUnique(OrgPerson model) {
        return RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_SYS_ORG_PE, model.getPersonId(), model.getOrgId());
    }

    private static String buildPrefixOrgList(OrgPerson model) {
        return RedisTemplateUtil.getRedisCacheKey(PREFIX_ORG_LIST, model.getPersonId());
    }

    private static String buildPrefixId(OrgPerson model) {
        return RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getOrgPersonId());
    }

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public OrgPersonDTO save(OrgPersonDTO dto) {
        checkUnique(dto);
        final OrgPerson model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public OrgPersonDTO update(OrgPersonDTO dto) {
        checkUnique(dto);
        final OrgPerson historyModel = Optional.ofNullable(getById(dto.getOrgPersonId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final OrgPerson model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(model);
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 批量添加
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<OrgPerson> mList) throws ApiException {
        try {
            if (!super.saveBatch(mList)) {
                throw new ApiException("批量添加失败");
            }
        } finally {
            clearCaches(mList);
        }
    }

    /**
     * 批量更新
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateBatchIds(List<OrgPerson> mList) {
        final List<String> ids = mList.stream().map(OrgPerson::getOrgPersonId).collect(toList());
        final List<OrgPerson> historyModelList = checkIds(ids);
        try {
            if (!super.updateBatchById(mList)) {
                throw new ApiException("批量更新失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
            ids.clear();
        }
    }

    /**
     * 删除，单个
     *
     * @param orgPersonId 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String orgPersonId) {
        final OrgPerson model = Optional.ofNullable(getById(orgPersonId)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(orgPersonId)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        final List<OrgPerson> historyModelList = checkIds(ids);
        try {
            if (!super.removeByIds(ids)) {
                throw new ApiException("批量删除失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(OrgPersonDTO dto) {
        final QueryWrapper<OrgPerson> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param orgPersonId 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String orgPersonId) {
        boolean exists = false;
        if (StringUtils.hasLength(orgPersonId)) {
            final OrgPerson model = getById(orgPersonId);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param orgPersonId 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public OrgPerson getById(String orgPersonId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, orgPersonId);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(orgPersonId), OrgPerson.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param orgPersonId 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public OrgPersonDTO getByIdDto(String orgPersonId) {
        final OrgPerson model = getById(orgPersonId);
        if (null != model) {
            return modelToDto(model);
        }
        return null;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public OrgPerson getOne(OrgPersonDTO dto) {
        final QueryWrapper<OrgPerson> queryWrapper = createQueryWrapper(dto);
        final OrgPerson model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public OrgPersonDTO getOneDto(OrgPersonDTO dto) {
        final OrgPerson model = getOne(dto);
        if (null == model) {
            return null;
        }
        final OrgPersonDTO newDto = modelToDto(model);
        model.freeData();
        return newDto;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<OrgPerson> getList(OrgPersonDTO dto) {
        final QueryWrapper<OrgPerson> queryWrapper = createQueryWrapper(dto);
        final List<OrgPerson> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<OrgPersonDTO> getListDto(OrgPersonDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<OrgPersonDTO> page(Page<OrgPerson> page, OrgPersonDTO dto) {
        final QueryWrapper<OrgPerson> queryWrapper = createQueryWrapper(dto, "org.");
        UserOperatorService.buildInSql(dto, queryWrapper);
        final IPage<OrgPersonDTO> iPage = baseMapper.page(page, queryWrapper);
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 分页数据
     *
     * @param page         分页对象
     * @param orgPersonDto 查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<OrgPersonDisplayDTO> orgPersonPage(Page<Person> page, OrgPersonDTO orgPersonDto) {
        final QueryWrapper<OrgPerson> queryWrapper = createQueryWrapper(orgPersonDto, "sp.");
        if (StringUtils.hasLength(orgPersonDto.getPersonName())) {
            queryWrapper.eq("p.person_name", orgPersonDto.getPersonName())
                    .or(q -> q.eq("p.account", orgPersonDto.getPersonName()))
                    .or(q -> q.eq("p.id_card", orgPersonDto.getPersonName()));
        }
        UserOperatorService.buildInSql(orgPersonDto, queryWrapper);
        final IPage<OrgPersonDisplayDTO> iPage = baseMapper.orgPersonPage(page, queryWrapper);
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 根据唯一性索引获得数据
     * <p>
     * param personId
     * param orgId
     *
     * @return 单条数据
     */
    @Transactional(readOnly = true)
    public OrgPerson getUniqueByPersonIdAndOrgId(String personId, String orgId) {
        final QueryWrapper<OrgPerson> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constants.PERSON_ID, personId);
        queryWrapper.eq(Constants.ORG_ID, orgId);
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_SYS_ORG_PE, personId, orgId);
        final OrgPerson model = redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getOne(queryWrapper, false), OrgPerson.class);
        queryWrapper.clear();
        return model;
    }

    /**
     * 验证唯一性索引
     *
     * @param dto 页面对象
     */
    @Transactional(readOnly = true)
    public void checkUnique(OrgPersonDTO dto) {
        final OrgPerson model = getUniqueByPersonIdAndOrgId(dto.getPersonId(), dto.getOrgId());
        if (null != model) {
            checkUnique(dto, model);
        }
    }

    /**
     * 验证唯一性索引
     *
     * @param dto   页面对象
     * @param model 根据约束字段查询出来的数据库对象
     */
    private void checkUnique(OrgPersonDTO dto, OrgPerson model) {
        if (!StringUtils.hasLength(dto.getOrgPersonId())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
        if (!dto.getOrgPersonId().equals(model.getOrgPersonId())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(OrgPerson model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(buildPrefixId(model));
        redisTemplateUtil.deleteByKey(buildPrefixOrgList(model));
        redisTemplateUtil.deleteByKey(buildPrefixUnique(model));
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<OrgPerson> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        List<String> ids = list.stream().map(OrgPersonService::buildPrefixId).collect(toList());
        if (!ids.isEmpty()) {
            redisTemplateUtil.deleteByKey(ids);
            ids.clear();
        }
        List<String> orgIds = list.stream().map(OrgPersonService::buildPrefixOrgList).collect(toList());
        if (!orgIds.isEmpty()) {
            redisTemplateUtil.deleteByKey(orgIds);
            orgIds.clear();
        }
        List<String> uniqueIds = list.stream().map(OrgPersonService::buildPrefixUnique).collect(toList());
        if (!uniqueIds.isEmpty()) {
            redisTemplateUtil.deleteByKey(uniqueIds);
            uniqueIds.clear();
        }

    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public OrgPersonDTO modelToDto(OrgPerson model) {
        if (null == model) {
            return null;
        }
        final OrgPersonDTO dto = new OrgPersonDTO();
        dto.setOrgPersonId(model.getOrgPersonId());
        dto.setAddTime(model.getAddTime());
        dto.setUpdateTime(model.getUpdateTime());
        dto.setPersonId(model.getPersonId());
        dto.setOrgId(model.getOrgId());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public OrgPerson dtoToModel(OrgPersonDTO dto) {
        if (null == dto) {
            return null;
        }
        final OrgPerson model = new OrgPerson();
        model.setOrgPersonId(dto.getOrgPersonId());
        model.setAddTime(dto.getAddTime());
        model.setUpdateTime(dto.getUpdateTime());
        model.setPersonId(dto.getPersonId());
        model.setOrgId(dto.getOrgId());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(OrgPersonDTO dto) {
        dto.setPersonIdDisplay(personService.idToDisplay(dto.getPersonId()));
        dto.setOrgIdDisplay(orgService.idToDisplay(dto.getOrgId()));
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<OrgPersonDTO> modelToDtoList(List<OrgPerson> list) {
        if (null == list) {
            return Collections.emptyList();
        }
        return list.stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<OrgPerson> dtoToModelList(List<OrgPersonDTO> list) {
        if (null == list) {
            return Collections.emptyList();
        }
        return list.stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<OrgPerson> createQueryWrapper(OrgPersonDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<OrgPerson> createQueryWrapper(OrgPersonDTO dto, String tableAlias) {
        final QueryWrapper<OrgPerson> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(dto.getPersonId())) {
                queryWrapper.eq(tableAlias + Constants.PERSON_ID, dto.getPersonId());
            }
            if (StringUtils.hasLength(dto.getOrgId())) {
                queryWrapper.eq(tableAlias + Constants.ORG_ID, dto.getOrgId());
            }
        }
        queryWrapper.orderByAsc(tableAlias + Constants.PERSON_ID);
        queryWrapper.orderByAsc(tableAlias + Constants.ORG_ID);
        return queryWrapper;
    }


    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */
    public List<OrgPerson> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<OrgPerson> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(OrgPerson::getOrgPersonId).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    /**
     * 获得当前机构下面的人员信息
     *
     * @param orgId 组织机构ID
     * @return 人员列表
     */
    public List<OrgPerson> getListByOrgId(String orgId) {
        final OrgPersonDTO query = new OrgPersonDTO();
        query.setOrgId(orgId);
        final QueryWrapper<OrgPerson> queryWrapper = createQueryWrapper(query);
        final List<OrgPerson> orgPersonList = list(queryWrapper);
        queryWrapper.clear();
        query.freeData();
        return orgPersonList;
    }

    /**
     * 根据人员ID查询组织信息ID集合
     *
     * @param personId 人员ID
     * @return 组织ID列表
     */
    public List<String> getOrgPersonByPersonId(String personId) {
        final List<OrgPerson> deptPersonList = getListByPersonId(personId);
        if (deptPersonList.isEmpty()) {
            return Collections.emptyList();
        }
        return deptPersonList.stream().map(OrgPerson::getOrgPersonId).collect(toList());
    }

    /**
     * 根据人员ID查询组织信息
     *
     * @param personId 人员ID
     * @return 组织列表
     */
    public List<OrgPerson> getListByPersonId(String personId) {
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ORG_LIST, personId);
        return redisTemplateUtil.getList(new CacheKey().setKey(key), () -> {
            final QueryWrapper<OrgPerson> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(Constants.PERSON_ID, personId);
            final List<OrgPerson> orgPersonList = list(queryWrapper);
            queryWrapper.clear();
            return orgPersonList;
        }, OrgPerson.class);
    }

    /**
     * 根据人员ID查询组织信息
     *
     * @param personId 人员ID
     * @return 组织列表
     */
    public List<Map<String, String>> getListDtoByPersonId(String personId) {
        final List<OrgPerson> orgPersonList = getListByPersonId(personId);
        if (null == orgPersonList || orgPersonList.isEmpty()) {
            return Collections.emptyList();
        }
        return orgPersonList.stream().map(this::buildDtoToMap).collect(toList());
    }

    private Map<String, String> buildDtoToMap(OrgPerson orgPerson) {
        final OrgPersonDTO orgPersonDto = modelToDto(orgPerson);
        final Map<String, String> map = new LinkedHashMap<>(2);
        map.put("orgId", orgPersonDto.getOrgId());
        map.put("orgIdDisplay", orgPersonDto.getOrgIdDisplay());
        return map;
    }

    public OrgService getOrgService() {
        return orgService;
    }

    public PersonService getPersonService() {
        return personService;
    }
}